<template>
  <div class="list">
    <sidebar v-model="active" class="sidebar">
      <sidebar-item
        :title="item.name"
        :key="item.id"
        v-for="item in categories"
        :to="{ name: 'list', query: { c_id: item.id } }"
      />
    </sidebar>
    <List
      class="products"
      finished-text="没有更多了"
      :finished="finished"
      :loading="loading"
      @load="load"
    >
      <card
        v-for="item in products"
        :key="item.id"
        :num="item.amount"
        :price="item.price.toFixed(2)"
        :title="item.name"
        :thumb="dalImg(item.coverImage)"
        @click-thumb="toDetail(item.id)"
      />
    </List>
  </div>
</template>
<script setup>
import { ref, computed } from "vue";
import { Sidebar, SidebarItem, Card, List } from "vant";
import { onBeforeRouteUpdate, useRoute, useRouter } from "vue-router";
import { dalImg } from "../utils/tools";
import { useCategory } from "../hooks/get-category";
import { useProduct } from "../hooks/get-products";

const route = useRoute();
const router = useRouter();
const { categories } = useCategory();
const { products, loadData, loading, finished } = useProduct();
const categoryId = ref(route.query.c_id);

const active = computed(() => {
  return categories.value.findIndex((item) => item.id == categoryId.value);
});

// const loadMoreData = () => {};
// loadData(categoryId.value);
onBeforeRouteUpdate((to, from) => {
  // console.log(to)
  categoryId.value = to.query.c_id;
  loadData(to.query.c_id, true);
});

const load = () => {
  // console.log("loading...");
  loadData(categoryId.value);
};
// 跳转商品详情页
const toDetail = (id) => {
  router.push({
    name: "detail",
    query: {
      id,
    },
  });
};
</script>
<style scoped lang="scss">
.list {
  display: flex;

  .products {
    flex: 1;
    overflow: auto;
  }
}
</style>
